﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.Model.ViewModel.Log;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.WebProvider;
namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class InsuranceWarrantyRecordController : BaseController
    {
        //
        // GET: /InsuranceWarrantyRecord/
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 保单号
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Index(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total).Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.InsuranceOrderId,
                o.WarrantyRecordNo,//报案单号
                o.Reporter,//报案人
                o.ReporterPhone,//报案人电话
                o.InsuranceOrder.UserName,//被保险人
                o.InsuranceOrder.UserPhone,//被保险人电话
                o.InsuranceOrder.CertificateNO,//被保险人证件号
                o.InsuranceOrder.InsuranceCategoryName,//保险类型
                o.InsuranceOrder.ProductName,//保险产品名称
                o.InsuranceOrder.ThirdOrderNO,//第三方保单号
                o.InsuranceOrder.InsuranceCompany,//第三方承保公司
                o.InsuranceOrder.InsuranceCompanyBranch,//承保公司分公司
                o.InsuranceOrder.SaleVendorName,//销售商户
                ServiceProviderName = o.ServiceProviderBranch == null ? "" : o.ServiceProviderBranch.ServiceProvider.ServiceProviderName,
                LastModifyTime = o.InsuranceOrder.LastModifyTime > DateTime.MinValue ? o.InsuranceOrder.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss") : "",//关单时间（最后编辑时间）
                o.ReceivableAmount,//应收金额
                ReceiptStatusDesc = EnumHelper.Instance.GetDescription(typeof(InsuranceWarrantyReceiptStatus), o.ReceiptStatus),//收款状态
                ReceiptTime = o.ReceiptTime.HasValue ? o.ReceiptTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",//收款时间
                o.PayableAmount,//应付金额
                PaymentStatusDesc = EnumHelper.Instance.GetDescription(typeof(InsuranceWarrantyPaymentStatus), o.PaymentStatus),//付款状态
                PaymentTime = o.PaymentTime.HasValue ? o.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""//收款时间
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }

        #region 导出收款状况清单
        /// <summary>  
        ///
        /// </summary>  
        /// <returns></returns>  
        public ActionResult ExportInsuranceWarrantyRecordDetails(string content)
        {
            InsuranceWarrantyRecordModel model = JsonConvert.DeserializeObject<InsuranceWarrantyRecordModel>(content);
            var total = 0;
            model.iDisplayStart = 0;
            model.iDisplayLength = int.MaxValue;
            var list =
                (from a in ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total)
                 join b in ServiceFactory.OpreateFinanceLogsServiceInstance.LoadEntities(n => n.FinanceType.Equals(1)) //FinanceType 1、收款
                        on a.ID equals b.LogTablePKID into temp
                 from c in temp.DefaultIfEmpty()
                 join d in ServiceFactory.InsuranceOrderServiceInstance.LoadEntities(n => true)
                        on a.InsuranceOrderId equals d.ID into temp1
                 from f in temp1.DefaultIfEmpty()
                 select new ExportInsuranceWarrantyRecordDetails
                 {
                     WarrantyRecordNo = a.WarrantyRecordNo, //报案单号
                     Reporter = a.Reporter, //报案人
                     ReporterPhone = a.ReporterPhone, //报案人电话
                     UserName = f.UserName, //被保险人
                     UserPhone = f.UserPhone, //被保险人电话
                     CertificateNO = f.CertificateNO, //被保险人证件号
                     InsuranceCategoryName = f.InsuranceCategoryName, //保险类型
                     ProductName = f.ProductName, //保险产品名称
                     InsuranceCompany = f.InsuranceCompany, //第三方承保公司
                     InsuranceCompanyBranch = f.InsuranceCompanyBranch, //承保公司分公司
                     SaleVendorName = f.SaleVendorName, //销售商户
                     lastModifyTimeTemp = f.LastModifyTime,//关单时间（最后编辑时间）
                     ReceivableAmount = a.ReceivableAmount, //应收金额
                     ReceiptStatus = a.ReceiptStatus,//收款状态 
                     ReceiptTimeTemp = a.ReceiptTime,//收款时间                      
                     PayableAmount = a.PayableAmount, //应付金额
                     PaymentStatus = a.PaymentStatus, //付款状态
                     PaymentTimeTemp = a.PaymentTime,////收款时间
                     OurBankAccount = c == null ? "" : c.OurBankAccount,
                     OurBankName = c == null ? "" : c.OurBankName,
                     OurBankAccountName = c == null ? "" : c.OurBankAccountName,
                     ThirdBankAccount = c == null ? "" : c.ThirdBankAccount,
                     ThirdBankName = c == null ? "" : c.ThirdBankName,
                     ThirdBankAccountName = c == null ? "" : c.ThirdBankAccountName,
                     BankTransactionSN = c == null ? "" : c.BankTransactionSN
                 }).ToList();
            var dt = ListToDatatableHelper.ToDataTable(list);
            dt.TableName = "List";
            List<DataTable> dataSoure = new List<DataTable> { dt };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\DownLoad\\Template\\InsuranceWarrantyRecordList.xlsx";
            string fileName = "导出收款状况清单-(" + DateTime.Now.ToString("yyyyMMdd") + ")";
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return Json(new object { });
        }
        #endregion

        #region 导出付款状况清单
        /// <summary>  
        ///
        /// </summary>  
        /// <returns></returns>  
        public ActionResult ExportPaymentInsuranceWarrantyRecordDetails(string content)
        {
            InsuranceWarrantyRecordModel model = JsonConvert.DeserializeObject<InsuranceWarrantyRecordModel>(content);
            var total = 0;
            model.iDisplayStart = 0;
            model.iDisplayLength = int.MaxValue;
            model.iSorts = "ID desc";
            var list =
                (from b in
                     ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total)
                 join a in
                     ServiceFactory.OpreateFinanceLogsServiceInstance.LoadEntities(n => n.FinanceType.Equals(2))//FinanceType 2、付款
                     on b.ID equals a.LogTablePKID into temp
                 from c in temp.DefaultIfEmpty()
                 join f in ServiceFactory.InsuranceOrderServiceInstance.LoadEntities(n => true) on b.InsuranceOrderId equals f.ID into temp1
                 from d in temp1.DefaultIfEmpty()
                 select new ExportInsuranceWarrantyRecordDetails
                 {
                     WarrantyRecordNo = b.WarrantyRecordNo, //报案单号
                     Reporter = b.Reporter, //报案人
                     ReporterPhone = b.ReporterPhone, //报案人电话
                     UserName = d.UserName, //被保险人
                     UserPhone = d.UserPhone, //被保险人电话
                     CertificateNO = d.CertificateNO, //被保险人证件号
                     InsuranceCategoryName = d.InsuranceCategoryName, //保险类型
                     ProductName = d.ProductName, //保险产品名称
                     InsuranceCompany = d.InsuranceCompany, //第三方承保公司
                     InsuranceCompanyBranch = d.InsuranceCompanyBranch, //承保公司分公司
                     SaleVendorName = d.SaleVendorName, //销售商户
                     lastModifyTimeTemp = d.LastModifyTime, //关单时间（最后编辑时间）
                     ReceivableAmount = b.ReceivableAmount, //应收金额
                     ReceiptStatus = b.ReceiptStatus,//收款状态 
                     ReceiptTimeTemp = b.ReceiptTime,//收款时间                      
                     PayableAmount = b.PayableAmount, //应付金额
                     PaymentStatus = b.PaymentStatus, //付款状态
                     PaymentTimeTemp = b.PaymentTime,//收款时间
                     OurBankAccount = c == null ? "" : c.OurBankAccount,
                     OurBankName = c == null ? "" : c.OurBankName,
                     OurBankAccountName = c == null ? "" : c.OurBankAccountName,
                     ThirdBankAccount = c == null ? "" : c.ThirdBankAccount,
                     ThirdBankName = c == null ? "" : c.ThirdBankName,
                     ThirdBankAccountName = c == null ? "" : c.ThirdBankAccountName,
                     BankTransactionSN = c == null ? "" : c.BankTransactionSN,
                     BankAccountName = b.ServiceProviderBranch != null ? b.ServiceProviderBranch.ServiceProvider.BankAccountName : ""
                 }).ToList();
            var dt = ListToDatatableHelper.ToDataTable(list);
            dt.TableName = "List";
            List<DataTable> dataSoure = new List<DataTable> { dt };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\DownLoad\\Template\\InsuranceWarrantyRecordPaymentList.xlsx";
            string fileName = "付款状况清单-(" + DateTime.Now.ToString("yyyyMMdd") + ")";
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return Json(new object { });
        }
        #endregion

        #region 收款对账详情
        public ActionResult ImportInsuranceWarrantyRecord()
        {
            ViewBag.ReturnInfo = TempData["Msg"];
            ViewBag.List = TempData["List"];
            return View();
        }
        #endregion

        #region  导入收款对账
        public ActionResult ImportInsuranceWarrantyRecordData()
        {
            var file = Request.Files["importFile"];
            if (file != null)
            {
                string fileName = file.FileName;
                string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

                if (!string.IsNullOrEmpty(strFileExt) && (strFileExt.ToLower() == "xls") ||
                    strFileExt.ToLower() == "xlsx")
                {
                    //upload to server
                    var saveFileName = FileHelper.UploadFile(file, Server);
                    string serverName = Server.MapPath(saveFileName);

                    var dt = ExcelHelper.ExcelToTable(serverName);
                    var userName = "被保险人姓名";
                    var ourBankAccount = "收款账号";
                    var receivedAmount = "收款金额";
                    var thirdBankAccount = "付款方账号";
                    var thirdBankName = "对方账号名称";
                    var bankTransactionSN = "收款交易流水号";
                    var thirdBankAccountName = "对方开户行";
                    var receiptTime = "交易时间";
                    if (dt.Columns.Contains(userName) &&
                        dt.Columns.Contains(ourBankAccount) &&
                        dt.Columns.Contains(receivedAmount) &&
                        dt.Columns.Contains(bankTransactionSN) &&
                        dt.Columns.Contains(thirdBankAccount) &&
                        dt.Columns.Contains(thirdBankName) &&
                        dt.Columns.Contains(thirdBankAccountName) &&
                        dt.Columns.Contains(receiptTime))
                    {
                        var result = new StringBuilder();
                        var sb = new StringBuilder();
                        int addSuccCount = dt.Rows.Count;
                        int updateSuccCount = 0;
                        int addFaileCount = 0;
                        bool status = true;
                        var table = "<table> <tr> <td>" + userName + "</td> <td>" + ourBankAccount + "</td>";
                        table += "<td>" + receivedAmount + "</td><td>" + thirdBankAccount + "</td><td>" + thirdBankName + "</td><td>" + bankTransactionSN + "</td>";
                        table += "<td>" + thirdBankAccountName + "</td><td>" + receiptTime + "</td><td>对账结果</td></tr>";
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            decimal receivedPrice = 0;
                            DataRow drItem = dt.Rows[i];
                            bool userNameIsOK = !string.IsNullOrWhiteSpace(drItem[userName].ToString());
                            bool ourBankAccountIsOK = !string.IsNullOrWhiteSpace(drItem[ourBankAccount].ToString());
                            bool anotherPartyBankNameIsOK = !string.IsNullOrWhiteSpace(drItem[thirdBankAccountName].ToString());
                            bool paymentAccountIsOK = !string.IsNullOrWhiteSpace(drItem[thirdBankAccount].ToString());
                            bool anotherPartyAccountNameOK = !string.IsNullOrWhiteSpace(drItem[thirdBankName].ToString());
                            bool receiptSerialNumberIsOK = !string.IsNullOrWhiteSpace(drItem[bankTransactionSN].ToString());
                            bool paymentedAmountIsOK = decimal.TryParse(
                                    string.IsNullOrWhiteSpace(drItem[receivedAmount].ToString())
                                        ? "0"
                                        : dt.Rows[i][receivedAmount].ToString(), out receivedPrice);
                            bool receiptTimeIsOK = !string.IsNullOrWhiteSpace(drItem[receiptTime].ToString());
                            if (paymentAccountIsOK && paymentedAmountIsOK && receiptSerialNumberIsOK && anotherPartyAccountNameOK && userNameIsOK && ourBankAccountIsOK && anotherPartyBankNameIsOK && receiptTimeIsOK)
                            {
                                InsuranceWarrantyRecord existEntity = null;
                                #region 更新

                                if (ServiceFactory.InsuranceWarrantyRecordServiceInstance.IsExistByUserNameReceivedPrice
                                    (CommonMethod.GetTrimStr(dt.Rows[i][userName].ToString()), receivedPrice, ref existEntity))
                                {
                                    #region 先记录日志
                                    var opreateFinanceLogs = new OpreateFinanceLogs
                                    {
                                        CreateBy = CurrentUser.UserAccount,
                                        CreateTime = DateTime.Now,
                                        LogTableName = "InsuranceWarrantyRecord",
                                        LogTablePKID = existEntity.ID,
                                        FinanceType = 1,
                                        Amount = receivedPrice,
                                        LogSubject = "案件处理信息-新增",
                                        LogContent = "本次收款金额:【" + receivedPrice + "】",
                                        OurBankAccount = CommonMethod.GetTrimStr(drItem[ourBankAccount].ToString()),
                                        ThirdBankAccount = CommonMethod.GetTrimStr(drItem[thirdBankAccount].ToString()),
                                        ThirdBankName = CommonMethod.GetTrimStr(drItem[thirdBankName].ToString()),
                                        ThirdBankAccountName = CommonMethod.GetTrimStr(drItem[thirdBankAccountName].ToString()),
                                        BankTransactionSN = CommonMethod.GetTrimStr(drItem[bankTransactionSN].ToString()),
                                        BankTransactionTime = Convert.ToDateTime(drItem[receiptTime].ToString())
                                    };
                                    ServiceFactory.OpreateFinanceLogsServiceInstance.AddEntities(opreateFinanceLogs);
                                    #endregion
                                    existEntity.ReceivedAmount = receivedPrice;
                                    existEntity.ReceiptTime = Convert.ToDateTime(drItem[receiptTime].ToString());
                                    existEntity.ReceiptStatus = (byte)InsuranceWarrantyReceiptStatus.Receipted;
                                    var flag =
                                        ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(existEntity);
                                    if (flag)
                                    {
                                        updateSuccCount++;
                                        status = true;
                                    }
                                    else
                                    {
                                        addFaileCount++;
                                        status = false;
                                    }
                                }
                                else
                                {
                                    addFaileCount++;
                                    status = false;
                                }
                                #endregion
                            }
                            string statusName = status ? "成功" : "失败";
                            table += "<tr><td>" + drItem[userName].ToString() + "</td><td>" + drItem[ourBankAccount].ToString() + "</td>";
                            table += "<td>" + drItem[receivedAmount].ToString() + "</td><td>" + drItem[thirdBankAccount].ToString() + "</td>";
                            table += "<td>" + drItem[thirdBankName].ToString() + "</td><td>" + drItem[bankTransactionSN].ToString() + "</td>";
                            table += "<td>" + drItem[thirdBankAccountName].ToString() + "</td><td>" + drItem[receiptTime].ToString() + "</td>";
                            table += "<td>" + statusName + "</td></tr>";
                        }
                        result.AppendLine("<dl><dt style='float:left;width:80px;'>对账条数:</dt><dd> " + addSuccCount);
                        result.AppendLine(" </dd> <dt style='float:left;width:80px;'>成功数量:</dt><dd> " + updateSuccCount);
                        result.AppendLine(" </dd><dt style='float:left;width:80px;'>失败数量:</dt><dd>" + addFaileCount + "</dl>");
                        //result.AppendFormat("更新成功数量:{0}\n,失败数量:{1}\n.提示信息:{2}\n", updateSuccCount,
                        //    addFaileCount, sb);
                        TempData["Msg"] = result;
                        TempData["List"] = table;
                    }
                    else
                    {
                        TempData["Msg"] = "导入列不合法，请下载导入模版。";
                    }
                }
                else
                {
                    TempData["Msg"] = "导入文件不合法，请选择Excel文件。";
                }
            }
            else
            {
                TempData["Msg"] = "请选择文件。";
            }

            return RedirectToAction("ImportInsuranceWarrantyRecord");
        }
        #endregion

        #region  付款对账详情
        public ActionResult ImportInsuranceWarrantyRecordPayment()
        {
            ViewBag.ReturnInfo = TempData["Msg"];
            ViewBag.List = TempData["List"];
            return View();
        }
        #endregion

        #region  导入付款款对账
        public ActionResult ImportInsuranceWarrantyRecordPaymentData()
        {
            var file = Request.Files["importFile"];
            if (file != null)
            {
                string fileName = file.FileName;
                string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

                if (!string.IsNullOrEmpty(strFileExt) && (strFileExt.ToLower() == "xls") ||
                    strFileExt.ToLower() == "xlsx")
                {
                    //upload to server
                    var saveFileName = FileHelper.UploadFile(file, Server);
                    string serverName = Server.MapPath(saveFileName);

                    var dt = ExcelHelper.ExcelToTable(serverName);
                    var warrantyRecordNo = "报案单号";
                    var ourBankAccount = "付款账号";
                    var receivedAmount = "付款金额";
                    var receiptTime = "付款时间";
                    var bankTransactionSN = "付款交易流水号";
                    if (dt.Columns.Contains(warrantyRecordNo) &&
                        dt.Columns.Contains(ourBankAccount) &&
                        dt.Columns.Contains(receivedAmount) &&
                        dt.Columns.Contains(bankTransactionSN) &&
                        dt.Columns.Contains(receiptTime))
                    {
                        var result = new StringBuilder();
                        var sb = new StringBuilder();
                        int addSuccCount = dt.Rows.Count;
                        int updateSuccCount = 0;
                        int addFaileCount = 0;
                        bool status = true;
                        var table = "<table> <tr> <td>" + warrantyRecordNo + "</td> <td>" + ourBankAccount + "</td>";
                        table += "<td>" + receivedAmount + "</td><td>" + bankTransactionSN + "</td>";
                        table += "<td>" + receiptTime + "</td><td>对账结果</td></tr>";
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            decimal receivedPrice = 0;
                            DataRow drItem = dt.Rows[i];
                            bool userNameIsOK = !string.IsNullOrWhiteSpace(drItem[warrantyRecordNo].ToString());
                            bool ourBankAccountIsOK = !string.IsNullOrWhiteSpace(drItem[ourBankAccount].ToString());
                            bool receiptSerialNumberIsOK = !string.IsNullOrWhiteSpace(drItem[bankTransactionSN].ToString());
                            bool paymentedAmountIsOK = decimal.TryParse(
                                    string.IsNullOrWhiteSpace(drItem[receivedAmount].ToString())
                                        ? "0"
                                        : dt.Rows[i][receivedAmount].ToString(), out receivedPrice);
                            bool receiptTimeIsOK = !string.IsNullOrWhiteSpace(drItem[receiptTime].ToString());
                            if (paymentedAmountIsOK && receiptSerialNumberIsOK && userNameIsOK && ourBankAccountIsOK && receiptTimeIsOK)
                            {
                                InsuranceWarrantyRecord existEntity = null;
                                #region 更新

                                if (ServiceFactory.InsuranceWarrantyRecordServiceInstance.IsExistWarrantyRecordNo
                                    (CommonMethod.GetTrimStr(dt.Rows[i][warrantyRecordNo].ToString()), receivedPrice, ref existEntity))
                                {
                                    #region 先记录日志
                                    var opreateFinanceLogs = new OpreateFinanceLogs
                                    {
                                        CreateBy = CurrentUser.UserAccount,
                                        CreateTime = DateTime.Now,
                                        LogTableName = "InsuranceWarrantyRecord",
                                        LogTablePKID = existEntity.ID,
                                        FinanceType = 2,
                                        Amount = receivedPrice,
                                        LogSubject = "案件处理信息-新增",
                                        LogContent = "本次付款金额:【" + receivedPrice + "】",
                                        OurBankAccount = CommonMethod.GetTrimStr(drItem[ourBankAccount].ToString()),
                                        ThirdBankAccountName = existEntity.ServiceProviderBranch != null ? existEntity.ServiceProviderBranch.ServiceProvider.BankAccountName : "",
                                        ThirdBankName = existEntity.ServiceProviderBranch != null ? existEntity.ServiceProviderBranch.ServiceProvider.BankName : "",
                                        ThirdBankAccount = existEntity.ServiceProviderBranch != null ? existEntity.ServiceProviderBranch.ServiceProvider.BankAccount : "",
                                        BankTransactionSN = CommonMethod.GetTrimStr(drItem[bankTransactionSN].ToString()),
                                        BankTransactionTime = Convert.ToDateTime(drItem[receiptTime].ToString())
                                    };
                                    ServiceFactory.OpreateFinanceLogsServiceInstance.AddEntities(opreateFinanceLogs);
                                    #endregion
                                    existEntity.PaymentedAmount = receivedPrice;
                                    existEntity.PaymentTime = Convert.ToDateTime(drItem[receiptTime].ToString());
                                    existEntity.PaymentStatus = (byte)InsuranceWarrantyPaymentStatus.Paymented;
                                    var flag =
                                        ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(existEntity);
                                    if (flag)
                                    {
                                        updateSuccCount++;
                                        status = true;
                                    }
                                    else
                                    {
                                        addFaileCount++;
                                        status = false;
                                    }
                                }
                                else
                                {
                                    addFaileCount++;
                                    status = false;
                                }
                                #endregion
                            }
                            string statusName = status ? "成功" : "失败";
                            table += "<tr><td>" + drItem[warrantyRecordNo].ToString() + "</td><td>" + drItem[ourBankAccount].ToString() + "</td>";
                            table += "<td>" + drItem[receivedAmount].ToString() + "</td>";
                            table += "<td>" + drItem[bankTransactionSN].ToString() + "</td>";
                            table += "<td>" + drItem[receiptTime].ToString() + "</td>";
                            table += "<td>" + statusName + "</td></tr>";
                        }
                        result.AppendLine("<dl><dt style='float:left;width:80px;'>对账条数:</dt><dd> " + addSuccCount);
                        result.AppendLine(" </dd> <dt style='float:left;width:80px;'>成功数量:</dt><dd> " + updateSuccCount);
                        result.AppendLine(" </dd><dt style='float:left;width:80px;'>失败数量:</dt><dd>" + addFaileCount + "</dl>");
                        //result.AppendFormat("更新成功数量:{0}\n,失败数量:{1}\n.提示信息:{2}\n", updateSuccCount,
                        //    addFaileCount, sb);
                        TempData["Msg"] = result;
                        TempData["List"] = table;
                    }
                    else
                    {
                        TempData["Msg"] = "导入列不合法，请下载导入模版。";
                    }
                }
                else
                {
                    TempData["Msg"] = "导入文件不合法，请选择Excel文件。";
                }
            }
            else
            {
                TempData["Msg"] = "请选择文件。";
            }

            return RedirectToAction("ImportInsuranceWarrantyRecordPayment");
        }
        #endregion

        #region 报价清单管理

        #region 报价清单列表页面
        public ActionResult QuotationIndex()
        {
            return View();
        }
        #endregion

        #region 报价清单列表数据
        public ActionResult QuotationList(AccessoriesQuotationModel model)
        {
            var total = 0;
            var list = ServiceFactory.AccessoriesQuotationServiceInstance.GetPagingList(model, out total);
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 导入报价清单表单页面
        public ActionResult ImportQuotationListForm()
        {
            ViewBag.ReturnInfo = TempData["Msg"];
            return View();
        }
        #endregion

        #region 导入报价清单提交数据 + ActionResult ImportQuotationList()
        public ActionResult ImportQuotationList()
        {
            var file = Request.Files["importFile"];
            if (file == null)
            {
                TempData["Msg"] = "请选择文件。";
                return RedirectToAction("ImportQuotationListForm");
            }

            string fileName = file.FileName;
            string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

            if (string.IsNullOrEmpty(strFileExt) || (strFileExt.ToLower() != "xls" && strFileExt.ToLower() != "xlsx"))
            {
                TempData["Msg"] = "导入文件不合法，请选择Excel文件。";
                return RedirectToAction("ImportQuotationListForm");
            }

            var saveFileName = FileHelper.UploadFile(file, Server);
            string serverName = Server.MapPath(saveFileName);

            var dt = ExcelHelper.ExcelToTable(serverName);
            if (dt.Rows.Count < 1)
            {
                TempData["Msg"] = "模板中没有数据";
                return RedirectToAction("ImportQuotationListForm");
            }
            var productNameTitle = "设备类型";
            var brandNameTitle = "品牌";
            var modelNameTitle = "型号";
            var modelCodeTitle = "型号编码";
            var accessoriesNameTitle = "配件类型";
            var accessoriesLevelNameTitle = "配件等级";
            var accessoriesLevelCodeTitle = "配件等级编码";
            var repairTypeNameTitle = "维修方式";
            var repairTypeCodeTitle = "维修方式编码";
            var serviceNameTitle = "服务商";
            var serviceCodeTitle = "服务商编码";
            var accessoriesPriceTitle = "报价";
            var accessoriesPriceTimeTitle = "报价时间";
            if (!dt.Columns.Contains(productNameTitle) || !dt.Columns.Contains(accessoriesLevelNameTitle) || !dt.Columns.Contains(brandNameTitle) ||
                !dt.Columns.Contains(accessoriesLevelCodeTitle) || !dt.Columns.Contains(modelNameTitle) || !dt.Columns.Contains(modelCodeTitle) ||
                !dt.Columns.Contains(accessoriesNameTitle) || !dt.Columns.Contains(repairTypeNameTitle) || !dt.Columns.Contains(serviceNameTitle) ||
                !dt.Columns.Contains(serviceCodeTitle) || !dt.Columns.Contains(accessoriesPriceTitle) || !dt.Columns.Contains(repairTypeCodeTitle)|| !dt.Columns.Contains(accessoriesPriceTimeTitle))
            {
                TempData["Msg"] = "导入列不合法，请下载导入模版。";
                return RedirectToAction("ImportQuotationListForm");
            }

            DateTime time = DateTime.Now;
            string userCount = CurrentUser.UserAccount;
            var result = new StringBuilder();
            int i = 1, wrongCount = 0, successCount = 0, repeaterCount = 0; //excel数据索引 1开始，错误数量，成功数量，重复数据数量
            var modelFac = ServiceFactory.ProductModelsServiceInstance;
            var accessoriesLevelFac = ServiceFactory.AccessoriesLevelServiceInstance;
            var serviceFac = ServiceFactory.ServiceProviderServiceInstance;
            var quotationFac = ServiceFactory.AccessoriesQuotationServiceInstance;
            //用于存储型号ID、配件等级Id、服务商Id。以免多次查询数据库
            Dictionary<string, long> dicModel = new Dictionary<string, long>();
            Dictionary<string, int> dicAccessoriesLevel = new Dictionary<string, int>();
            Dictionary<string, int> dicService = new Dictionary<string, int>();

            foreach (DataRow dr in dt.Rows)
            {
                i++;
                //型号编码
                string modelCode = dr[modelCodeTitle].ToString();
                //配件等级编码
                string accessoriesLevelCode = dr[accessoriesLevelCodeTitle].ToString();
                //服务商编码
                string serviceCode = dr[serviceCodeTitle].ToString();
                //维修方式编码
                string serviceTypeCode = dr[repairTypeCodeTitle].ToString();
                //报价
                decimal accessoriesPrice = new decimal(0.0);
                //报价时间
                DateTime accessoriesPriceTime ;
                bool tagTime = DateTime.TryParse(dr[accessoriesPriceTimeTitle].ToString(), out accessoriesPriceTime);
                if (!tagTime)
                {
                    result.Append(string.Format("第{0}行有错：报价时间格式不正确。<br/>", i));
                    wrongCount++;
                    continue;
                }

                bool price = decimal.TryParse(dr[accessoriesPriceTitle].ToString(), out accessoriesPrice);
                if (!price || accessoriesPrice <= new decimal(0.0))
                {
                    result.Append(string.Format("第{0}行有错：报价只能为正数。<br/>", i));
                    wrongCount++;
                    continue;
                }
                if (string.IsNullOrWhiteSpace(modelCode) || string.IsNullOrWhiteSpace(accessoriesLevelCode) || string.IsNullOrWhiteSpace(serviceCode) || string.IsNullOrWhiteSpace(serviceTypeCode))
                {
                    result.Append(string.Format("第{0}行有错：型号编码、配件等级编码、维修方式编码和服务商编码皆不能为空。<br/>", i));
                    wrongCount++;
                    continue;
                }
                modelCode = modelCode.Trim();
                accessoriesLevelCode = accessoriesLevelCode.Trim();
                serviceCode = serviceCode.Trim();
                //1、查找型号ID
                long modelId = 0;
                if (dicModel.ContainsKey(modelCode))
                    modelId = dicModel[modelCode];
                else
                {
                    var model = modelFac.LoadEntities(t => t.ModelCode == modelCode).FirstOrDefault();
                    if (model == null || model.ID < 1)
                    {
                        result.Append(string.Format("第{0}行有错：未查找到相应的型号信息；型号编码：{1}。<br/>", i, modelCode));
                        wrongCount++;
                        continue;
                    }
                    else
                    {
                        modelId = model.ID;
                        dicModel.Add(modelCode, modelId);
                    }
                }
                //2、配件等级ID
                int accessoriesLevelId = 0;
                if (dicAccessoriesLevel.ContainsKey(accessoriesLevelCode))
                    accessoriesLevelId = dicAccessoriesLevel[accessoriesLevelCode];
                else
                {
                    var accessoriesLevel = accessoriesLevelFac.LoadEntities(t => t.AccessoriesLevelCode == accessoriesLevelCode).FirstOrDefault();
                    if (accessoriesLevel == null || accessoriesLevel.ID < 1)
                    {
                        result.Append(string.Format("第{0}行有错：未查找到相应的配件类型信息；配件类型编码：{1}。<br/>", i, accessoriesLevelCode));
                        wrongCount++;
                        continue;
                    }
                    else
                    {
                        accessoriesLevelId = accessoriesLevel.ID;
                        dicAccessoriesLevel.Add(accessoriesLevelCode, accessoriesLevelId);
                    }
                }
                //3、服务商ID
                int serviceId = 0;
                if (dicService.ContainsKey(serviceCode))
                    serviceId = dicService[serviceCode];
                else
                {
                    var service = serviceFac.LoadEntities(t => t.ServiceCode == serviceCode).FirstOrDefault();
                    if (service == null || service.ID < 1)
                    {
                        result.Append(string.Format("第{0}行有错：未查找到相应的服务商信息；服务商编码：{1}。<br/>", i, serviceCode));
                        wrongCount++;
                        continue;
                    }
                    else
                    {
                        serviceId = service.ID;
                        dicService.Add(serviceCode, serviceId);
                    }
                }
                //维修方式
                byte serviceType = GetServiceType(serviceTypeCode);
                try
                {
                    //判断供应商是否已经对某个型号的配件配置了价格
                    var entity = quotationFac.LoadEntities(t => t.IsAvailable == true && t.ServiceProviderId == serviceId && t.ProductModelId == modelId && t.AccessoriesLevelId == accessoriesLevelId && t.ServiceType ==serviceType ).OrderByDescending(t => t.ID).FirstOrDefault();
                    bool re = false;
                    if (entity != null && entity.ID > 0)
                    {
                        //验证价格是否有变化
                        if (entity.QuotationPrice != accessoriesPrice)
                        {
                            //修改他为不可用状态
                            entity.IsAvailable = false;
                            quotationFac.UpdateEntities(entity);
                            repeaterCount++;
                            result.Append(string.Format("第{0}行重复：已将旧数据设置为不可用状态；旧数据主键ID：{1}。型号编码：{2};配件类型编码：{3}；服务商编码：{4}。<br/>", i, entity.ID, modelCode, accessoriesLevelCode, serviceCode));

                            re = quotationFac.AddEntities(new AccessoriesQuotation()
                            {
                                IsAvailable = true,
                                CreateTime = time,
                                LastModifyTime = time,
                                QuotationTime = accessoriesPriceTime,
                                ProductModelId = modelId,
                                AccessoriesLevelId = accessoriesLevelId,
                                ServiceType = serviceType,
                                ServiceProviderId = serviceId,
                                QuotationPrice = accessoriesPrice,
                                CreateBy = userCount,
                                LastModifyBy = userCount
                            }).ID > 0;

                        }
                        else
                        {
                            result.Append(string.Format("第{0}行重复：未做任何修改。<br/>", i));
                            re = true;
                        }
                    }
                    else
                    {
                        re = quotationFac.AddEntities(new AccessoriesQuotation()
                        {
                            IsAvailable = true,
                            CreateTime = time,
                            LastModifyTime = time,
                            QuotationTime = accessoriesPriceTime,
                            ProductModelId = modelId,
                            AccessoriesLevelId = accessoriesLevelId,
                            ServiceType = serviceType,
                            ServiceProviderId = serviceId,
                            QuotationPrice = accessoriesPrice,
                            CreateBy = userCount,
                            LastModifyBy = userCount
                        }).ID > 0;

                    }
                    if (re)
                        successCount++;
                    else
                        wrongCount++;
                }
                catch (Exception ex)
                {
                    result.Append(string.Format("第{0}行系统异常：异常信息：{1}。<br/>", i, ex.ToString()));
                }
            }
            TempData["Msg"] = string.Format("总数量：{0}；成功数量：{1}；失败数量：{2}；更新数量：{3}。<br/>", dt.Rows.Count, successCount, wrongCount, repeaterCount) + result.ToString();
            return RedirectToAction("ImportQuotationListForm");
        }
        #endregion

        #region 导出报价清单excel + ActionResult ExportQuotationList()

        //选择模板内容页面
        public ActionResult ExportQuotationList()
        {
            return View();
        }

        #region 提交数据 生成excel并导出
        /// <summary>
        /// 提交数据 生成excel并导出
        /// </summary>
        /// <param name="accessoriesLevelParams">配件等级ID</param>
        /// <param name="modelParams">型号</param>
        /// <param name="serviceProviderId"></param>
        /// <param name="repairType"></param>
        /// <returns></returns>
        public ActionResult ExportQuotation(string accessoriesLevelParams, string modelParams, int serviceProviderId, string repairType)
        {
            //配件等级ID集合
            List<int> accessoriesIds = new List<int>();
            if (!string.IsNullOrEmpty(accessoriesLevelParams))
                accessoriesIds = accessoriesLevelParams.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList();
            //型号
            List<long> modelIds = new List<long>();
            if (!string.IsNullOrEmpty(modelParams))
                modelIds = modelParams.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int64.Parse).ToList();
            //维修方式
            List<short> repairTypes = new List<short>();
            if (!string.IsNullOrEmpty(repairType))
                repairTypes = repairType.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int16.Parse).ToList();
            //服务商信息
            var serviceProvider = ServiceFactory.ServiceProviderServiceInstance.LoadEntities(t => t.ID == serviceProviderId).AsNoTracking().FirstOrDefault();

            //配件等级列表
            var accessoriesLevelList = (from a in ServiceFactory.AccessoriesLevelServiceInstance.LoadEntities(t => accessoriesIds.Contains(t.ID))
                                        join b in ServiceFactory.AccessoriesTypeServiceInstance.LoadEntities(t => true) on a.AccessoriesTypeID equals b.ID into temp1
                                        from c in temp1.DefaultIfEmpty()
                                        join d in ServiceFactory.ProductTypeServiceInstance.LoadEntities(t => true) on a.ProductTypeID equals d.ID into temp2
                                        from f in temp2.DefaultIfEmpty()
                                        select new
                                        {
                                            a.AccessoriesLevelName,
                                            a.AccessoriesLevelCode,
                                            c.AccessoriesName,
                                            f.ProductCode,
                                            f.ProductName
                                        }).ToList();

            //设备型号列表
            var modelList = (from a in ServiceFactory.ProductModelsServiceInstance.LoadEntities(t => modelIds.Contains(t.ID))
                             join b in ServiceFactory.ProductBrandsServiceInstance.LoadEntities(t => true) on a.BrandId equals b.ID into temp1
                             from c in temp1.DefaultIfEmpty()
                             join d in ServiceFactory.ProductTypeServiceInstance.LoadEntities(t => true) on c.ProductTypeId equals d.ID into temp2
                             from f in temp2.DefaultIfEmpty()
                             select new
                             {
                                 a.ModelName,
                                 a.ModelCode,
                                 c.BrandName,
                                 f.ProductCode,
                                 f.ProductName
                             }).ToList();

            var data = (from a in accessoriesLevelList
                        from b in modelList
                        from c in repairTypes
                        where a.ProductCode == b.ProductCode
                        orderby a.ProductCode,b.BrandName,b.ModelCode, a.AccessoriesName,a.AccessoriesLevelCode,c
                        select new
                        {
                            a.AccessoriesLevelName,
                            a.AccessoriesLevelCode,
                            a.AccessoriesName,
                            a.ProductName,
                            b.ModelName,
                            b.ModelCode,
                            b.BrandName,
                            RepairType = EnumHelper.Instance.GetDescription(typeof(InsuranceWarrantyMaintenanceType), c),
                            RepairTypeCode = CommonMethod.GenerateCode("WXFS", c.ToString(), 6),
                            ServiceName = serviceProvider.ServiceProviderName,
                            ServiceCode = serviceProvider.ServiceCode
                        }).ToList();

            var dt = ListToDatatableHelper.ToDataTable(data);
            dt.TableName = "List";
            List<DataTable> dataSoure = new List<DataTable> { dt };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string fileName = "报价清单-(" + DateTime.Now.ToString("yyyyMMdd") + ")";
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\DownLoad\\Template\\QuotationList.xlsx";
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return Json(new object { });
        }
        #endregion

        #endregion

        #region 修改报价清单状态 + ActionResult AccessoriesQuotationUpdateStatus(int id, bool isAvailable)
        public ActionResult AccessoriesQuotationUpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.AccessoriesQuotationServiceInstance.LoadEntities(t => t.ID == id).FirstOrDefault();
            var success = false;
            if (entity != null)
            {
                //设为启用状态的时候需要判断当前服务商的这款产品类型配件的报价是否已经存在
                if (isAvailable)
                {
                    var temp = ServiceFactory.AccessoriesQuotationServiceInstance.LoadEntities(t => t.IsAvailable == true && t.ServiceProviderId == entity.ServiceProviderId && t.ProductModelId == entity.ProductModelId && t.AccessoriesLevelId == entity.AccessoriesLevelId && t.ServiceType == entity.ServiceType).OrderByDescending(t => t.ID).FirstOrDefault();
                    if (temp != null && temp.ID > 0)
                    {
                        return Json(new
                        {
                            success = false,
                            message = "修改失败，已经存在此产品配件的报价"
                        });
                    }
                }
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.AccessoriesQuotationServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion

        #region 修改报价 + ActionResult SaveQuotationPrice(int ID, decimal QuotationPrice)
        [HttpPost]
        public ActionResult SaveQuotationPrice(int ID, decimal QuotationPrice)
        {
            var entity = ServiceFactory.AccessoriesQuotationServiceInstance.LoadEntities(t => t.ID == ID).FirstOrDefault();
            var success = false;
            if (entity != null)
            {

                entity.QuotationPrice = QuotationPrice;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.AccessoriesQuotationServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                Result = success,
                Message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion

        #region 根据维修方式编码差接触维修方式枚举编号 + byte GetServiceType(string serviceTypeCode)
        /// <summary>
        /// 根据维修方式编码拆解出维修方式枚举编号
        /// </summary>
        /// <param name="serviceTypeCode">维修方式编码</param>
        /// <returns></returns>
        public byte GetServiceType(string serviceTypeCode)
        {
            string temp = serviceTypeCode.Substring(serviceTypeCode.Length - 6);
           return Convert.ToByte(temp);
        }
        #endregion

        #endregion
    }
}